<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="权限名称" prop="permissionName">
        <el-input
          v-model="queryParams.permissionName"
          placeholder="请输入权限名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限编码" prop="permissionCode">
        <el-input
          v-model="queryParams.permissionCode"
          placeholder="请输入权限编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限类型" prop="permissionType">
        <el-select v-model="queryParams.permissionType" placeholder="请选择权限类型" clearable>
          <el-option
            v-for="dict in pm_permission_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in pm_permission_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">
          <el-icon><Search /></el-icon>搜索
        </el-button>
        <el-button size="small" @click="resetQuery">
          <el-icon><Refresh /></el-icon>重置
        </el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="small"
          @click="handleAdd"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Plus /></el-icon>新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Edit /></el-icon>修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:team:manage']"
        >
          <el-icon><Delete /></el-icon>删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          size="small"
          @click="handleTree"
          v-hasPermi="['pm:team:view']"
        >
          <el-icon><Grid /></el-icon>树形结构
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="permissionList" @selection-change="handleSelectionChange" v-show="!showTree">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="权限名称" align="center" prop="permissionName" />
      <el-table-column label="权限编码" align="center" prop="permissionCode" />
      <el-table-column label="权限类型" align="center" prop="permissionType">
        <template #default="scope">
          <dict-tag 
            :options="pm_permission_type || []" 
            :value="scope.row.permissionType"
            v-if="pm_permission_type && pm_permission_type.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.permissionType || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="权限路径" align="center" prop="permissionPath" />
      <el-table-column label="父权限" align="center" prop="parentPermissionName" />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag 
            :options="pm_permission_status || []" 
            :value="scope.row.status"
            v-if="pm_permission_status && pm_permission_status.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.status || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:team:view']"
          >
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 树形结构显示 -->
    <el-table v-loading="loading" :data="permissionTree" @selection-change="handleSelectionChange" v-show="showTree">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="权限名称" align="left" prop="permissionName" show-overflow-tooltip />
      <el-table-column label="权限编码" align="center" prop="permissionCode" show-overflow-tooltip />
      <el-table-column label="权限类型" align="center" prop="permissionType">
        <template #default="scope">
          <dict-tag 
            :options="pm_permission_type || []" 
            :value="scope.row.permissionType"
            v-if="pm_permission_type && pm_permission_type.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.permissionType || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="权限路径" align="center" prop="permissionPath" show-overflow-tooltip />
      <el-table-column label="排序" align="center" prop="sortOrder" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag 
            :options="pm_permission_status || []" 
            :value="scope.row.status"
            v-if="pm_permission_status && pm_permission_status.length > 0"
          />
          <el-tag v-else type="info">{{ scope.row.status || '未知' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:team:view']"
          >
            <el-icon><View /></el-icon>查看
          </el-button>
          <el-button
            size="small"
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Edit /></el-icon>修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:team:manage']"
          >
            <el-icon><Delete /></el-icon>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0 && !showTree"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

     <!-- 添加或修改团队权限对话框 -->
     <el-dialog :title="title" v-model="open" width="500px" append-to-body>
       <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
         <el-form-item label="权限名称" prop="permissionName">
           <el-input v-model="form.permissionName" placeholder="请输入权限名称" :disabled="isView" />
         </el-form-item>
         <el-form-item label="权限编码" prop="permissionCode">
           <el-input v-model="form.permissionCode" placeholder="请输入权限编码" :disabled="isView" />
         </el-form-item>
         <el-form-item label="权限类型" prop="permissionType">
           <el-select v-model="form.permissionType" placeholder="请选择权限类型" :disabled="isView">
             <el-option
               v-for="dict in pm_permission_type"
               :key="dict.value"
               :label="dict.label"
               :value="dict.value"
             />
           </el-select>
         </el-form-item>
         <el-form-item label="权限描述" prop="description">
           <el-input v-model="form.description" type="textarea" placeholder="请输入权限描述" :disabled="isView" />
         </el-form-item>
         <el-form-item label="父权限" prop="parentId">
           <el-tree-select
             v-model="form.parentId"
             :data="permissionTree"
             :props="{ children: 'children', label: 'permissionName', value: 'permissionId' }"
             placeholder="请选择父权限"
             clearable
             check-strictly
             :disabled="isView"
           />
         </el-form-item>
         <el-form-item label="权限路径" prop="permissionPath">
           <el-input v-model="form.permissionPath" placeholder="请输入权限路径" :disabled="isView" />
         </el-form-item>
         <el-form-item label="权限图标" prop="permissionIcon">
           <el-input v-model="form.permissionIcon" placeholder="请输入权限图标" :disabled="isView" />
         </el-form-item>
         <el-form-item label="排序" prop="sortOrder">
           <el-input-number v-model="form.sortOrder" :min="0" :max="999" :disabled="isView" />
         </el-form-item>
         <el-form-item label="状态" prop="status">
           <el-radio-group v-model="form.status" :disabled="isView">
             <el-radio
               v-for="dict in pm_permission_status"
               :key="dict.value"
               :label="dict.value"
             >{{ dict.label }}</el-radio>
           </el-radio-group>
         </el-form-item>
         <el-form-item label="备注" prop="remark">
           <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isView" />
         </el-form-item>
       </el-form>
       <template #footer>
         <div class="dialog-footer">
           <el-button type="primary" @click="submitForm" v-if="!isView">确 定</el-button>
           <el-button @click="cancel">取 消</el-button>
         </div>
       </template>
     </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, toRefs } from 'vue'
import type { FormInstance } from 'element-plus'
import { listTeamPermission, getTeamPermission, delTeamPermission, addTeamPermission, updateTeamPermission, getPermissionTree } from "@/api/pm/team";
import { Search, Refresh, Plus, Edit, Delete, Grid, View } from '@element-plus/icons-vue';
import RightToolbar from '@/components/RightToolbar/index.vue';
import DictTag from '@/components/DictTag/index.vue';
import Pagination from '@/components/Pagination/index.vue';

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 获取字典数据
const { pm_permission_type, pm_permission_status } = toRefs<any>(proxy?.useDict('pm_permission_type', 'pm_permission_status'))

// 表单引用
const formRef = ref<FormInstance>()
const queryFormRef = ref<FormInstance>()

// 响应式数据
const loading = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const showTree = ref(false)
const total = ref(0)
const permissionList = ref<any[]>([])
const permissionTree = ref<any[]>([])
const title = ref("")
const open = ref(false)
const isView = ref(false)

// 查询参数
const queryParams = reactive<any>({
  pageNum: 1,
  pageSize: 10,
  permissionName: null,
  permissionCode: null,
  permissionType: null,
  status: null,
})

// 表单参数
const form = ref<any>({
  permissionId: null,
  permissionName: null,
  permissionCode: null,
  permissionType: "menu",
  description: null,
  parentId: 0,
  permissionPath: null,
  permissionIcon: null,
  sortOrder: 0,
  status: "0",
  remark: null
})

// 表单校验
const rules = reactive({
  permissionName: [
    { required: true, message: "权限名称不能为空", trigger: "blur" }
  ],
  permissionCode: [
    { required: true, message: "权限编码不能为空", trigger: "blur" }
  ],
  permissionType: [
    { required: true, message: "权限类型不能为空", trigger: "change" }
  ]
})

// 生命周期
onMounted(() => {
  getList()
  getPermissionTreeData()
})

// 方法定义
/** 查询团队权限列表 */
const getList = () => {
  loading.value = true;
  listTeamPermission(queryParams).then(response => {
    permissionList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取权限列表失败:', error);
    permissionList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 获取权限树数据 */
const getPermissionTreeData = () => {
  getPermissionTree().then(response => {
    permissionTree.value = response.data || [];
  }).catch(error => {
    console.error('获取权限树失败:', error);
    permissionTree.value = [];
  });
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}

// 表单重置
const reset = () => {
  form.value = {
    permissionId: null,
    permissionName: null,
    permissionCode: null,
    permissionType: "menu",
    description: null,
    parentId: 0,
    permissionPath: null,
    permissionIcon: null,
    sortOrder: 0,
    status: "0",
    remark: null
  };
  proxy?.$nextTick(() => {
    formRef.value?.resetFields();
  });
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  proxy?.$nextTick(() => {
    queryFormRef.value?.resetFields();
  });
  handleQuery();
}

/** 树形结构按钮操作 */
const handleTree = () => {
  showTree.value = !showTree.value;
  if (showTree.value) {
    getPermissionTreeData();
  } else {
    getList();
  }
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.permissionId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  isView.value = false;
  open.value = true;
  title.value = "添加团队权限";
}

/** 查看按钮操作 */
const handleView = (row: any) => {
  reset();
  const permissionId = row?.permissionId || ids.value[0]
  getTeamPermission(permissionId).then(response => {
    form.value = response.data;
    isView.value = true;
    open.value = true;
    title.value = "查看团队权限";
  });
}

/** 修改按钮操作 */
const handleUpdate = (row?: any) => {
  reset();
  const permissionId = row?.permissionId || ids.value[0]
  getTeamPermission(permissionId).then(response => {
    form.value = response.data;
    isView.value = false;
    open.value = true;
    title.value = "修改团队权限";
  });
}

/** 提交按钮 */
const submitForm = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (form.value.permissionId != null) {
        updateTeamPermission(form.value).then(response => {
          proxy?.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          getPermissionTreeData();
        });
      } else {
        addTeamPermission(form.value).then(response => {
          proxy?.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
          getPermissionTreeData();
        });
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = (row?: any) => {
  const permissionIds = row?.permissionId ? [row.permissionId] : ids.value
  proxy?.$modal.confirm('是否确认删除团队权限编号为"' + permissionIds.join(',') + '"的数据项？').then(function() {
    return delTeamPermission(permissionIds);
  }).then(() => {
    getList();
    getPermissionTreeData();
    proxy?.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
</script>
